<template>
    <el-form ref="form" label-width="80px" style="height: 100%;display: flex;flex-direction: column;">
        <el-form-item label="开卡客户">
            <div style="height:62px">
                <el-select v-model="ginfo.name" filterable remote placeholder="请输入关键词" :remote-method="searchguest" :loading="loading" @change="selectguest" default-first-option style="float: left;margin-right: 10px;">
                    <el-option v-for="item in guestlist" :key="item.id" :label="item.name" :value="item.id" style="height: 68px">
                        <div style="display: flex; flex-direction: column">
                            <div>
                                <span style="font-weight: 900;">{{item.name}}</span>
                                <span style="float: right;font-size: 11px;color: #dc35af;">{{item.shopname}}</span>
                            </div>
                            <span style="font-size: 12px;margin-left: 10px;">{{item.phone}}</span>
                        </div>
                    </el-option>
                </el-select>
                <div style="width:400px; float: left" v-show="ginfo.id">
                    <el-card :body-style="{ padding: '0px' }">
                        <el-row>
                            <div style="float: left;height: 60px;margin-right: 10px">
                                <img :src="ginfo.headurl" style="border-radius: 50%; width: 50px; height:50px;padding: 5px">
                            </div>
                            <div style="float: left;height: 60px;">
                                <p style="margin: 0px; height: 30px">
                                    <span @click="openGuestPage(ginfo.id)" style="cursor:pointer;color:#f50">{{ginfo.name}}</span>
                                    <span style="margin-left: 10px;font-size: 13px;color: #999;"><i class="iconfont el-icon-h-dianhua1"></i> {{ginfo.phone}}</span>
                                    <span style="margin-left: 10px;font-size: 13px;color: #999;"><i class="iconfont el-icon-h-yue01"></i> {{ginfo.balance}}</span>
                                    <span style="margin-left: 10px;font-size: 13px;color: #999;"><i class="iconfont el-icon-h-zengsong"></i> {{ginfo.giftbalance}}</span>
                                </p>
                                <p style="margin: 0px; height: 30px">
                                    <span style="font-size: 13px;color: #999;"><i class="iconfont el-icon-h-level"></i> {{ginfo.vipcard}}</span> 产品折扣：
                                    <span style="font-size: 13px;color: #999;">{{ginfo.goodsdiscount}}</span> 项目折扣：
                                    <span style="font-size: 13px;color: #999;">{{ginfo.subjectdiscount}}</span>
                                </p>
                            </div>
                        </el-row>
                    </el-card>
                </div>
                <div style="width:400px; float: left;margin-left: 10px" v-show="ginfo.id">
                    <el-input type="textarea" :rows="3" v-model="ginfo.remarks">
                    </el-input>
                </div>
            </div>
        </el-form-item>
        <el-form-item label="开卡列表" style="height: 100%;" class="tableClass">
            <el-button style="width: 80px" icon="plus" type="primary" size="small" @click="addRow(orderListRef)">加一行</el-button>
            <el-table :data="orderlist" :stripe="true" height="100%" show-summary :summary-method="summary">
                <el-table-column prop="rowtype" label="类型" width="95">
                    <template scope="scope">
                        <el-input placeholder="类型" icon="search" :value="returnValue(scope)" size="small" :ref="makeIndex(scope.$index, 1, orderListRef)" @focus="setIndex(scope.$index, 1, orderListRef)" @blur="checkValue($event, scope)" @keyup.enter.native="searchOpenCardType($event, scope.row)">
                            <i slot="suffix" class="el-icon-search" style="line-height: 32px;width: 25px;cursor: pointer;" @click="firstPopupType(scope)"></i>
                        </el-input>
                    </template>
                </el-table-column>
                <el-table-column prop="name" label="名称" width="180">
                    <template scope="scope">
                        <el-input :ref="makeIndex(scope.$index, 2, orderListRef)" @focus="setIndex(scope.$index, 2, orderListRef)" :value="scope.row.name" size="small" @blur="blurcheck($event, scope.row.name)" @keyup.enter.native="searchTypeGoods($event, scope)">
                            <i slot="suffix" class="el-icon-search" style="line-height: 32px;width: 25px;cursor: pointer;" @click="firstPopupGoods(scope)"></i>
                        </el-input>
                    </template>
                </el-table-column>
                <el-table-column prop="price" label="标准价格">
                    <template scope="scope">{{scope.row.price+'元'}}</template>
                </el-table-column>
                <el-table-column prop="num" label="数量" width="80">
                    <template scope="scope">
                        <el-input :ref="makeIndex(scope.$index, 3, orderListRef)" @focus="setIndex(scope.$index, 3, orderListRef)" v-model="scope.row.num" size="small" v-if="scope.row.rowtype == 1 || scope.row.rowtype == 2" @keyup.native="changeamount(scope.row)" @keyup.enter.native="nextInput(orderListRef)"></el-input>
                        <span v-else>{{scope.row.num}}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="discount" label="折扣（0-1）" width="100">
                    <template scope="scope">
                        <el-input :ref="makeIndex(scope.$index, 4, orderListRef)" @focus="setIndex(scope.$index, 4, orderListRef)" style="width:80px" v-model="scope.row.discount" size="small" @keyup.native="changeamount(scope.row)" @keyup.enter.native="nextInput(orderListRef)"></el-input>
                    </template>
                </el-table-column>
                <el-table-column prop="amount" label="小计" width="100">
                    <template scope="scope">
                        <el-input :ref="makeIndex(scope.$index, 5, orderListRef)" @focus="setIndex(scope.$index, 5, orderListRef)" v-model="scope.row.amount" size="small" @keyup.native="changediscount(scope.row)" @keyup.enter.native="nextInput(orderListRef)"></el-input>
                    </template>
                </el-table-column>
                <el-table-column prop="usemoney" label="现金">
                    <template scope="scope">
                        <el-input :ref="makeIndex(scope.$index, 6, orderListRef)" @focus="setIndex(scope.$index, 6, orderListRef)" class="money" placeholder="元" v-model="scope.row.usemoney" size="small" @keyup.enter.native="nextInput(orderListRef)"></el-input>
                    </template>
                </el-table-column>
                <el-table-column prop="usebalance" label="余额">
                    <template scope="scope">
                        <el-input class="money" :ref="makeIndex(scope.$index, 7, orderListRef)" @focus="setIndex(scope.$index, 7, orderListRef)" placeholder="元" v-model="scope.row.usebalance" size="small" @keyup.enter.native="nextInput(orderListRef)"></el-input>
                    </template>
                </el-table-column>
                <el-table-column prop="usegiftbalance" label="赠送余额">
                    <template scope="scope">
                        <el-input class="money" :ref="makeIndex(scope.$index, 8, orderListRef)" @focus="setIndex(scope.$index, 8, orderListRef)" placeholder="元" v-model="scope.row.usegiftbalance" size="small" @keyup.enter.native="nextInput(orderListRef)"></el-input>
                    </template>
                </el-table-column>
                <el-table-column prop="validity" label="有效期">
                    <template scope="scope">{{scope.row.validity?scope.row.validity+'天':'用完为止'}}</template>
                </el-table-column>
                <el-table-column prop="isgift" label="赠">
                    <template scope="scope">
                        <el-input style="width:50px" :ref="makeIndex(scope.$index, 9, orderListRef)" @focus="setIndex(scope.$index, 9, orderListRef)" :value="returnValue(scope)" @blur="checkValue($event, scope)" size="small" @keyup.enter.native="selectTrue($event, scope)"></el-input>
                    </template>
                </el-table-column>
                <el-table-column prop="cost" label="扣成本%">
                    <template scope="scope">
                        <el-input style="width:60px" :ref="makeIndex(scope.$index, 10, orderListRef)" @focus="setIndex(scope.$index, 10, orderListRef)" v-model="scope.row.cost" size="small" @keyup.enter.native="nextInput(orderListRef)"></el-input>
                    </template>
                </el-table-column>
                <el-table-column label="移除">
                    <template scope="scope">
                        <el-button size="mini" type="danger" @click="deleterow(scope.$index, orderlist)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-form-item>
        <el-form-item label="开卡描述">
            <el-input type="textarea" v-model="order.remarks" placeholder="请输入开卡描述，方便了解该订单。（可忽略）"></el-input>
        </el-form-item>
        <div style="padding: 10px">
            <el-button style="float:right" type="primary" icon="upload2" @click="submitorder" v-qx="quanxian.add">保存并结账</el-button>
            <el-button style="margin: 0px" type="danger" icon="close" @click="closewin">取消关闭</el-button>
        </div>
    </el-form>
</template>
<script>
import C from '#/src/common/common.js'
import S from '#/src/shop/search.js'
import P from '#/src/shop/popup.js'
import D from '#/src/common/datas.js'
import keyUpRef from '#/src/shop/keyupref.js'
import Guest from '#/src/shop/guest.js'
import headImg from '#/static/img/headimg.jpg'

export default {
    name: 'order',
    props: ['order'],
    data() {
        return {
            ginfo: this.order.ginfo,
            orderlist: this.order.orderlist,
            //杂项
            guestlist: [], // 选择客户杂项
            loading: true,
            orderListRef: D.openCard.inputRef,
            quanxian: {
                add: 'opencards_add',
                jiezhang: 'opencards_jiezhang',
                fanjiezhang: 'opencards_fan',
                dayin: 'opencards_print',
                fenpei: 'opencards_fen',
                fanfenpei: 'opencards_fanfen',
                chongxinfenpei: 'opencards_chongxin'
            }
        }
    },
    methods: C.assign(keyUpRef, {
        returnValue(scope) {
            if (scope.column.property == 'rowtype') {
                return scope.row[scope.column.property] == 1 ? '产品' : scope.row[scope.column.property] == 2 ? '项目' : '卡项'
            } else if (scope.column.property == 'fuwutype') {
                return scope.row[scope.column.property] == 1 ? '点客' : '轮牌'
            } else {
                return scope.row[scope.column.property] == 1 ? '是' : '否'
            }
        },
        checkValue(e, scope) {
            e.target.value = this.returnValue(scope)
        },
        selectTrue(e, scope) {
            let v = e.target.value
            let isHave = false
            D.trueOrFalse.forEach((row) => {
                if (row.name == v || row.value == v) {
                    isHave = true
                    if (scope.row[scope.column.property] != row.value) {
                        scope.row[scope.column.property] = row.value
                        // 如果是赠送赋值为零
                        this.changeStatus(scope.row)
                    }
                    e.target.value = row.name
                    this.nextInput(this.orderListRef)
                }
            })
            if (!isHave) {
                C.error('请输入0或1进行选择！')
                e.target.select()
            }
        },
        blurcheck: function(e, value) {
            e.target.value = value
        },
        searchOpenCardType: async function(e, row) {
            // 搜索数据
            if (!C.openLoading()) return false
            let typelist = await S.searchOpenCardType(e.target.value)
            let data = typelist.length == 1 ? typelist[0] : await P.openCardTypePopup(e.target.value, typelist)
            C.closeLoading()
            if (data && data.id) {
                let newdata = C.copy(D.orderListRow)
                newdata.rowtype = data.id
                row = Object.assign(row, newdata)
                this.nextInput(this.orderListRef)
            }
        },
        async firstPopupType(scope) {
            this.setIndex(scope.$index, 1, this.orderListRef)
            let data = await P.openCardTypePopup()
            if (data && data.id) {
                let newdata = C.copy(D.orderListRow)
                newdata.rowtype = data.id
                scope.row = Object.assign(scope.row, newdata)
                this.nextInput(this.orderListRef)
            }
        },
        async firstPopupGoods(scope) {
            this.setIndex(scope.$index, 2, this.orderListRef)
            let data = await P.typeGoodsPopup({ keywords: '', rowtype: scope.row.rowtype })
            if (data && data.id) {
                let index = C.inarray({ rowtype: scope.row.rowtype, id: data.id }, this.orderlist)
                // 不存在插入，存在进行如下判断
                // 有数据同一行跳转，有数据不同行提示不能重复
                if (index == -1) {
                    scope.row.id = data.id
                    scope.row.name = data.name
                    scope.row.price = data.price
                    scope.row.amount = data.price
                    scope.row.brandid = data.brandid
                    scope.row.validity = data.validity
                    scope.row.cardtype = data.category
                    scope.row.goodsnum = data.nums
                    this.nextInput(this.orderListRef)
                } else if (scope.$index == index) {
                    this.nextInput(this.orderListRef)
                } else {
                    C.error('选择数据重复！')
                    return false
                }
            }
        },
        searchTypeGoods: async function(e, scope) {
            // 判断是否选择行类型
            if (!scope.row.rowtype) {
                C.error('请先选择行类型！')
                return false
            }
            // 开启防重复点击
            if (!C.openLoading()) return false
            let data = await S.searchTypeGoods({ keywords: e.target.value, rowtype: scope.row.rowtype })
            data = data.data.length == 1 ?
                data.data[0] :
                await P.typeGoodsPopup({ keywords: e.target.value, rowtype: scope.row.rowtype }, data)
            C.closeLoading()
            if (data && data.id) {
                let index = C.inarray({ rowtype: scope.row.rowtype, id: data.id }, this.orderlist)
                // 不存在插入，存在进行如下判断
                // 有数据同一行跳转，有数据不同行提示不能重复
                if (index == -1) {
                    scope.row.id = data.id
                    scope.row.name = data.name
                    scope.row.price = data.price
                    scope.row.amount = data.price
                    scope.row.brandid = data.brandid
                    scope.row.validity = data.validity
                    scope.row.cardtype = data.category
                    scope.row.goodsnum = data.nums
                    this.nextInput(this.orderListRef)
                } else if (scope.$index == index) {
                    this.nextInput(this.orderListRef)
                } else {
                    C.error('选择数据重复！')
                    return false
                }
            }
        },
        selectguest: function(id) {
            this.guestlist.forEach((row) => {
                if (row.id == id) {
                    row.headurl = row.headurl != 0 ? row.headurl : headImg
                    this.ginfo = Object.assign({}, row)
                    this.addRow(this.orderListRef)
                }
            })
        },
        searchguest: async function(search) {
            if (search != '') {
                this.loading = true
                let data = { pagesize: 30, currentpage: 1, search: search }
                let guestData = await Guest.getDepartmentGuestList(data)
                this.loading = false
                this.guestlist = guestData.data  
            }
        },
        deleterow: C.deleterow,
        closewin: function() {
            C.closeBrowserWindow()
        },
        summary: function(param) {
            const { columns, data } = param
            const sums = []
            columns.forEach((column, index) => {
                if (index === 0) {
                    sums[index] = '合计'
                    return
                }
                if (index == 5 || index == 6 || index == 7 || index == 8) {
                    const values = data.map(item => Number(item[column.property]))
                    if (!values.every(value => isNaN(value))) {
                        sums[index] = values.reduce((prev, curr) => {
                            const value = Number(curr)
                            if (!isNaN(value)) {
                                return prev + curr
                            } else {
                                return prev
                            }
                        }, 0)
                        sums[index] = sums[index].toFixed(2)
                    } else {
                        sums[index] = 'N/A'
                    }
                }
            })
            return sums
        },
        submitorder: async function() {
            if (!this.ginfo.id) {
                C.error('请选择客户！')
                return false
            }
            let allotPrice = 0
            if (!this.orderlist.length) {
                C.error('请选择卡项！')
                return false
            } else {
                for (var i = 0; i < this.orderlist.length; i++) {
                    allotPrice += this.orderlist[i].amount * 1
                    if (this.orderlist[i].num <= 0) {
                        C.error('数量必须大于零！')
                        return false
                    }
                    if (this.orderlist[i].goodsnum && this.orderlist[i].num > this.orderlist[i].goodsnum) {
                        C.error('选择的产品数量超出了库存数量！')
                        return false
                    }
                }
            }
            let usebalance = 0,
                usegiftbalance = 0
            for (let i = 0; i < this.orderlist.length; i++) {
                if (!this.orderlist[i].id || !this.orderlist[i].rowtype) {
                    C.error('第' + (i + 1) + '行，请选择品项！')
                    return false
                }
                if (this.orderlist[i].cost > 100) {
                    C.error('第' + (i + 1) + '行，扣除成本不能超过商品自身价格！')
                    return false
                }
                if (this.orderlist[i].num <= 0 || this.orderlist[i].discount < 0) {
                    C.error('第' + (i + 1) + '行数量或者扣填写不正确！')
                    return false
                }
                let uamount = C.accAdd(C.accAdd(this.orderlist[i].usemoney, this.orderlist[i].usebalance), this.orderlist[i].usegiftbalance)
                if (C.accSub(this.orderlist[i].amount, uamount) != 0) {
                    C.error('第' + (i + 1) + '行金额填写不对称！')
                    return false
                }
                // 判断余额或者赠送余额是否足够
                usebalance += Number(this.orderlist[i].usebalance)
                usegiftbalance += Number(this.orderlist[i].usegiftbalance)
            }

            let initConfig = JSON.parse(C.getLocalStorage('initConfig'))
            if (initConfig.isqian) {
                if (usebalance > this.ginfo.balance) {
                    if (!confirm('该客户余额已不足，会产生欠款，确定要继续吗？')) {
                        return false
                    }
                }
            } else {
                if (usebalance > this.ginfo.balance) {
                    C.error('客户账户余额不足以支付当前订单！')
                    return false
                }
            }

            if (usegiftbalance > this.ginfo.giftbalance) {
                C.error('客户的账户赠送余额不足以支付当前订单！')
                return false
            }
            this.order.usegiftbalance = this.fenpeijine.usegiftbalance
            this.order.usebalance = this.fenpeijine.usebalance
            this.order.usemoney = this.fenpeijine.usemoney
            this.order.usecard = this.fenpeijine.usecard

            this.order.crossShop = 0
            let shopid = JSON.parse(C.getLocalStorage('initConfig')).shopid
            if (this.ginfo.departmentid != 0 && shopid != this.ginfo.departmentid) {
                this.order.crossShop = 1
            }
            
            let datas = {
                ginfo: this.ginfo,
                cards: this.orderlist,
                money: allotPrice,
                order: this.order,
                remarks: this.order.remarks
            }
            /*console.log(datas)
            return false*/
            let tijiaourl = this.order.id ? '/shop/card/editopencard' : '/shop/card/opencard'
            if (!C.openLoading()) return false
            let res = await C.ajax(tijiaourl, { data: JSON.stringify(datas) }, 'post')
            if (res) {
                C.closeLoading()
                C.success(res.data.info)
                this.$emit('goto', {
                    id: res.data.id,
                    status: 0,
                    index: 1
                })
            }
        },
        changeamount: function(row) {
            row.amount = (row.price * row.num * row.discount).toFixed(2)
            row.isgift = row.amount == 0 ? 1 : 0
        },
        changediscount: function(row) {
            row.discount = (row.amount / (row.num * row.price)).toFixed(4)
            row.isgift = row.amount == 0 ? 1 : 0
        },
        changeStatus: function(row) {
            row.discount = row.isgift ? 0 : 1
            this.changeamount(row)
        },
        openGuestPage(id) {
            Guest.openGuestPage(id)
        }
    }),
    computed: {
        fenpeijine: function() {
            let o = { putong: 0, kahao: 0, qikahao: 0, zancun: 0, zongji: 0, usemoney: 0, usebalance: 0, usegiftbalance: 0, usecard: 0 }
            this.orderlist.forEach((row) => {
                if (row.consumetype == 1) {
                    o.putong += Number(row.amount)
                    if (row.cardtype == 1) {
                        o.qikahao += Number(row.usebalance) + Number(row.usegiftbalance)
                    }
                } else if (row.consumetype == 2) {
                    o.kahao += Number(row.amount)
                } else {
                    o.zancun += Number(row.amount)
                }
                o.zongji += Number(row.amount)

                o.usemoney += Number(row.usemoney)
                o.usebalance += Number(row.usebalance)
                o.usegiftbalance += Number(row.usegiftbalance)
                o.usecard = 0
            })
            return o
        }
    },
    watch: {
        'order.ginfo.id': async function () {
            let data = await Guest.getGuestInfo(this.order.ginfo.id)
            if (data) this.ginfo = data
        }
    }
}
</script>
<style>
</style>